package nio.base;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class ScatterGatherTest {

    private FileChannel channel;

    @Before
    public void openFile() throws FileNotFoundException {
        channel = new RandomAccessFile("ScatterGatherTest.txt", "rw").getChannel();
    }

    @After
    public void close() throws IOException {
        channel.close();
    }

    @Test
    public void gather() throws IOException {

        String hStr = "header";
        ByteBuffer header = ByteBuffer.allocate(hStr.length());
        header.put(hStr.getBytes());
        header.flip();

        String bStr = "body";
        ByteBuffer body = ByteBuffer.allocate(bStr.length());
        body.put(bStr.getBytes());
        body.flip();

        ByteBuffer[] array = {header, body};
        channel.write(array);
    }

    @Test
    public void scatter() throws IOException {

        String hStr = "header";
        ByteBuffer header = ByteBuffer.allocate(hStr.length());

        String bStr = "body";
        ByteBuffer body = ByteBuffer.allocate(bStr.length());

        ByteBuffer[] array = {header, body};
        channel.read(array);

        header.flip();
        body.flip();
        System.out.println(Charset.forName("utf-8").newDecoder().decode(header));
        System.out.println(Charset.forName("utf-8").newDecoder().decode(body));
    }
}
